package com.zzx.project.config;

import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @ClassName: TraceIdInterceptor
 * @Description: tid生成器
 * @Author zhouzhixin
 * @Date 2021/5/8
 * @Version 1.0
 */
@Component
public class TraceIdInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tid = getTraceId();
        MDC.put("tid", tid);
        //将traceId添加进响应头
        response.addHeader("tid", tid);
        return true;
    }

    public static String getTraceId() {
        return String.format("%s", UUID.randomUUID());
    }

}
